import logging
from app.database.database import SessionLocal
from app.services.upload_chunk_service import clean_expired_tasks
from sqlalchemy.orm import Session
import threading
import time
from datetime import datetime, timedelta

# 配置日志记录器
logger = logging.getLogger(__name__)

def run_cleanup_task():
    """
    运行清理任务，清理过期的上传任务
    """
    try:
        db = SessionLocal()
        try:
            logger.info("开始清理过期上传任务")
            result = clean_expired_tasks(db)
            logger.info(f"清理任务完成: {result.get('message', '')}")
        finally:
            db.close()
    except Exception as e:
        logger.error(f"清理任务失败: {str(e)}")

def start_cleanup_scheduler():
    """
    启动清理任务调度器
    """
    def scheduler():
        # 24小时运行一次
        interval = 24 * 60 * 60
        
        while True:
            try:
                run_cleanup_task()
            except Exception as e:
                logger.error(f"清理任务调度器错误: {str(e)}")
                
            # 等待下一次执行
            logger.debug(f"清理任务调度器将在{interval}秒后再次运行")
            time.sleep(interval)
    
    # 在后台线程中运行
    thread = threading.Thread(target=scheduler, daemon=True)
    thread.start()
    logger.info("清理任务调度器已启动") 